<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :rules="queryForm" :inline="true" v-show="showSearch"
             label-width="68px">
      <el-form-item label="企业名称" prop="compName">
        <el-input
          v-model="queryParams.compName"
          placeholder="请输入企业名称"
          clearable
          size="small"
          maxlength="30"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="用户姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户姓名"
          clearable
          size="small"
          maxlength="30"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="服务时间" label-width="100">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="info" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>


      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['server:record:add']"
          >新增
          </el-button>
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="handleDelete"
            v-hasPermi="['server:record:remove']"
          >删除
          </el-button>
          <el-button
            type="info"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['server:record:export']"
          >导出
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
      </el-row>
    </el-form>

    <el-table v-loading="loading" :data="serviceRecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center" type="index" key="serviceId" prop="serviceId"
                       v-if="columns[0].visible"/>
      <el-table-column label="企业名称" align="center" key="compName" prop="compName" v-if="columns[1].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="用户姓名" align="center" key="userName" prop="userName" v-if="columns[2].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="用户电话" align="center" key="userPhone" prop="userPhone" v-if="columns[3].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="服务人员" align="center" key="serviceName" prop="serviceName" v-if="columns[4].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="服务人员电话" align="center" key="serverPhone" prop="serverPhone" v-if="columns[5].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="服务事件" align="center" key="serviceMatter" prop="serviceMatter" v-if="columns[6].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="图片" align="center" key="matterImg" prop="matterImg" v-if="columns[7].visible"
                       :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <div
            style="width: 120px;height: 120px;display:flex;align-items:center; justify-content:center; border: dashed darkgrey 1px">
            <el-image v-if="scope.row.matterImg != '' && scope.row.matterImg != null" style="width: auto;  height: auto"
                      :src="scope.row.matterImg"
                      :preview-src-list="srcList"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="服务时间" align="center" key="serviceTime" prop="serviceTime" v-if="columns[8].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="服务类型" align="center" :formatter="typeFormat"
                       v-if="columns[9].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="服务状态" align="center" width="100" key="serviceStatus" v-if="columns[10].visible"
                       :formatter="statusFormat"
                       :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.serviceStatus === '0'"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['server:record:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="scope.row.serviceStatus === '0'"
            v-hasPermi="['server:record:remove']"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleLook(scope.row)"
            v-else
            v-hasPermi="['server:record:edit']"
          >查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改报修记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="企业名称" prop="compName">
              <el-select
                v-model="form.compName" style="width: 100%"
                placeholder="请选择"
                clearable
                @change="selectGet">
                <el-option
                  v-for="item in compOptions"
                  :key="item.compId"
                  :label="item.compName"
                  :value="item.compId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用户姓名" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户姓名" maxlength="30"/>
            </el-form-item>
            <el-form-item label="用户电话" prop="userPhone">
              <el-input v-model="form.userPhone" placeholder="请输入用户电话" maxlength="20"/>
            </el-form-item>
            <el-form-item label="服务人员" prop="serviceName">
              <el-select v-model="form.serviceName" style="width: 100%"
                         @change="changePhone">
                <el-option
                  v-for="item in serverOptions"
                  :key="item.userId"
                  :label="item.userName"
                  :value="item.userId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="图片" prop="matterImg">
              <el-upload
                v-if="form.matterImg"
                ref="upload"
                action=""
                :show-file-list="false"
                list-type="picture-card"
                accept=".jpg,.jpeg,.png,.JPG,.JPEG"
                :auto-upload="false"
                :on-change="getFile">
                <img :src="form.matterImg" style="width: 148px;height: 148px;border-radius: 6px">
                <el-button slot="trigger" size="small" type="primary">选取图片</el-button>
                <div slot="tip" class="el-upload__tip">只能上传一张jpg/png图片，且不超过500kb</div>
              </el-upload>
              <el-upload
                v-else
                ref="upload"
                action=""
                :show-file-list="false"
                list-type="picture-card"
                accept=".jpg,.jpeg,.png,.JPG,.JPEG"
                :auto-upload="false"
                :on-change="getFile">
                <el-button slot="trigger" size="small" type="primary">选取图片</el-button>
                <div slot="tip" class="el-upload__tip">只能上传一张jpg/png图片，且不超过500kb</div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务人员电话" prop="serverPhone">
              <el-input v-model="form.serverPhone" placeholder="请输入服务人员电话" maxlength="20"/>
            </el-form-item>
            <el-form-item label="服务事件" prop="serviceMatter">
              <el-input v-model="form.serviceMatter" placeholder="请输入服务事件" maxlength="200"/>
            </el-form-item>
            <el-form-item label="服务时间" prop="serviceTime">
              <el-date-picker style="width: 100%"
                              v-model="form.serviceTime"
                              size="small"
                              value-format="yyyy-MM-dd HH:mm"
                              type="datetime"
                              clearable
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="服务类型" prop="serviceType">
              <el-select
                clearable v-model="form.serviceType" style="width: 100%" placeholder="请选择">
                <el-option
                  v-for="dict in typeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="服务状态" prop="serviceStatus">
              <el-select
                clearable v-model="form.serviceStatus" style="width: 100%" placeholder="请选择">
                <el-option
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" maxlength="200"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看报修记录对话框 -->
    <el-dialog :title="title" :visible.sync="look" width="800px" append-to-body>
      <el-form :model="form" label-width="125px" size="mini">
        <el-row>
          <el-col :span="12">
            <el-form-item label="企业名称："> {{ form.compName }}</el-form-item>
            <el-form-item label="用户姓名："> {{ form.userName }}</el-form-item>
            <el-form-item label="用户电话："> {{ form.userPhone }}</el-form-item>
            <el-form-item label="服务人员"> {{ form.serviceName }}</el-form-item>
            <el-form-item label="服务人员电话："> {{ form.serverPhone }}</el-form-item>
            <el-form-item label="服务事件：">
              {{ form.serviceMatter }}
            </el-form-item>
            <el-form-item label="备注：">
              {{ form.remark }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务时间：">
              {{ form.serviceTime }}
            </el-form-item>
            <el-form-item label="图片：">
              <div
                style="width: 120px;height: 120px;display:flex;align-items:center; justify-content:center; border: dashed darkgrey 1px">
                <el-image v-if="form.matterImg != ''" style="width: auto;  height: auto" :src="form.matterImg"
                          :preview-src-list="srcList"/>
              </div>
            </el-form-item>
            <el-form-item label="服务类型：">
              {{selectDictLabel(typeOptions, form.serviceType)}}
            </el-form-item>
            <el-form-item label="服务状态：">
              {{selectDictLabel(statusOptions, form.serviceStatus)}}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>

import {
  addRecord,
  changeStatus,
  delRecord,
  exportRecord,
  getRecord,
  listRecord,
  updateRecord
} from "../../../api/server/estates/serviceRecord";

import {listUser} from "../../../api/system/user";
import {listRole} from "../../../api/system/role";

export default {
  name: 'serviceRecord',
  comments: {},
  data() {
    return {
      //预览图片列表
      srcList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 预约表格数据
      serviceRecordList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      look: false,
      //企业选项
      compOptions: [],
      // 状态字典
      statusOptions: [],
      //类型字典
      typeOptions: [],
      //日期范围
      dateRange: [],
      //服务人员列表
      serverOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        compName: undefined,
        userName: undefined,
        date: undefined,
      },
      // 表单参数
      form: {},
      //列信息
      columns: [
        {key: 0, label: "序号", visible: true},
        {key: 1, label: "企业名称", visible: true},
        {key: 2, label: "用户姓名", visible: true},
        {key: 3, label: "用户电话", visible: true},
        {key: 4, label: "服务人员", visible: true},
        {key: 5, label: "服务人员电话", visible: true},
        {key: 6, label: "服务事件", visible: true},
        {key: 7, label: "图片", visible: true},
        {key: 8, label: "服务时间", visible: true},
        {key: 9, label: "服务类型", visible: true},
        {key: 10, label: "服务状态", visible: true},
      ],
      queryForm: {
        userName: [{pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/, message: '不能为特殊字符', trigger: 'blur'}],
        compName: [{pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/, message: '不能为特殊字符', trigger: 'blur'}],
      },
      // 表单校验
      rules: {
        userPhone: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ],
        compName: [
          {required: true, message: '企业名称不能为空', trigger: 'change'}
        ],
        userName: [
          {required: true, message: '用户姓名不能为空', trigger: 'blur'}
        ],
        serviceName: [
          {message: '服务人员姓名不能为空', trigger: 'blur'}
        ],
        serverPhone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'change'
          }
        ],
        serviceTime: [
          {required: true, message: '服务时间不能为空', trigger: 'blur'}
        ],
        serviceType: [
          {required: true, message: '服务类型不能为空', trigger: 'change'}
        ],
        serviceStatus: [
          {required: true, message: '服务状态不能为空', trigger: 'change'}
        ],
      }
    }
  },
  created() {
    this.getList()
    this.getDicts('t_service_status').then(response => {
      this.statusOptions = response.data
    })
    this.getDicts('t_service_type').then(response => {
      this.typeOptions = response.data
    })
    this.serversClick()
  },
  methods: {
    /** 查询报修记录列表 */
    getList() {
      this.loading = true
      listRecord(this.addDateRange1(this.queryParams, this.dateRange)).then(response => {
        this.serviceRecordList = response.rows
        let arr = response.rows
        for (let i in arr) {
          if (arr[i].serverPhone != null) {
            this.serviceRecordList[i].serverPhone = arr[i].serverPhone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
          }
          if (arr[i].userPhone != null) {
            this.serviceRecordList[i].userPhone = arr[i].userPhone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
          }
        }
        this.total = response.total
        this.loading = false
        for (let i in this.serviceRecordList) {
          this.srcList.push(this.serviceRecordList[i].matterImg)
        }
      })
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.serviceStatus)
    },
    //类型字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.serviceType)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.$refs['queryForm'].validate(valid => {
        if (valid) {
          this.getList()
        }
      })
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.queryParams.params.beginTime = ''
      this.queryParams.params.endTime = ''
      this.resetForm('queryForm')
      this.handleQuery()
    },
    //表单重置
    reset() {
      // 表单参数
      this.form = {
        compId: undefined,
        compName: undefined,
        serverId: undefined,
        userName: undefined,
        serverPhone: undefined,
        serviceName: undefined,
        userPhone: undefined,
        serviceMatter: undefined,
        matterImg: null,
        serviceTime: undefined,
        serviceType: undefined,
        serviceStatus: undefined,
        remark: undefined,
      },
        this.resetForm('form')
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.serviceId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    //获取下拉框中的label值与value值
    selectGet(vId) { // 这个vId也就是value值
      let obj = {};
      obj = this.compOptions.find((item) => { // 这里的userList就是上面遍历的数据源
        return item.compId === vId; // 筛选出匹配数据
      });
      this.form.compId = obj.compId;
      this.form.compName = obj.compName;
    },
    //获取服务人员下拉表
    serversClick() {
      listUser({roleId: 109}).then(res => {
        let newList = res.rows
        for (let i in newList) {
          for (let j in newList[i].roles) {
            if (newList[i].roles[j].roleId === 109) {
              this.serverOptions.push(newList[i])
            }
          }
        }
      })
    },
    //获取选择的服务人员信息并赋值给form表单中的数据
    changePhone(e) {
      for (let i in this.serverOptions) {
        if (e === this.serverOptions[i].userId) {
          this.form.serviceName = this.serverOptions[i].userName
          this.form.serverPhone = this.serverOptions[i].phoneNumber
        }
      }
    },
    //上传图片
    getFile(file) {
      const isLt2M = file.size / 1024 / 1024 / 2 < 0.5;
      if (!isLt2M) {
        file = ""
        this.$message.info('上传头像图片大小不能超过500kb!');
      } else {
        this.getBase64(file.raw).then(res => {
          this.form.matterImg = res
        });
      }
    },
    //限制图片上传大小
    // beforeAvatarUpload(file) {
    //   const isLt2M = file.size / 1024 / 1024 / 2 < 0.5;
    //   if (!isLt2M) {
    //     this.$message.info('上传头像图片大小不能超过500kb!');
    //   }
    //   return isLt2M;
    // },
    //将本地图片转成base64
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      getRecord().then(response => {
        this.compOptions = response.comps;
        this.open = true;
        this.title = '添加报修记录'
        this.$nextTick(() => {
          this.$refs.upload.clearFiles();
        })
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const serviceId = row.serviceId || this.ids
      getRecord(serviceId).then(response => {
        this.form = response.data;
        this.compOptions = response.comps;
        this.open = true
        this.title = '修改报修记录'
        this.$nextTick(() => {
          this.$refs.upload.clearFiles();
        })
      })
    },
    handleLook(row) {
      this.reset()
      const serviceId = row.serviceId || this.ids
      getRecord(serviceId).then(response => {
        this.form = response.data
        this.look = true
        this.title = '查看报修记录'
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.serviceId != undefined) {
            updateRecord(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addRecord(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const serviceIds = row.serviceId || this.ids
      if (serviceIds.length === 0) {
        this.$confirm('请选择需要删除的记录')
      } else {
        this.$confirm('是否确认删除该数据项?', '警告', {
          cancelButtonClass: 'btn-custom-cancel',
          closeOnClickModal: false,
          type: 'warning'
        }).then(function () {
          return delRecord(serviceIds);
        }).then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有报修表数据项?', '提示', {
        cancelButtonClass: 'btn-custom-cancel',
        closeOnClickModal: false,
        type: 'info'
      }).then(function () {
        return exportRecord(queryParams)
      }).then(response => {
        this.download(response.msg)
      })
    }
  }
}
</script>
